package com.wlyuan.open.scanner.application.handler.table;

import com.alibaba.fastjson.JSON;
import com.wlyuan.open.scanner.application.annotation.TableScannerName;
import com.wlyuan.open.scanner.constant.AddressTypeEnum;
import com.wlyuan.open.scanner.constant.Constants;
import com.wlyuan.open.scanner.constant.ScannerCodeEnum;
import com.wlyuan.open.scanner.constant.TableEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author lijing
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
@TableScannerName(isDefault = false, tableName = TableEnum.ADDR)
public class AddrTableToIncrHandler extends BaseTableToIncrHandler {
    private static final String ADDR_TYPE = "Addr_Type";

    @Override
    public List<String> handler(String tableName, String data, String beforeData) {
        var businessParams = params(data);
        if (StringUtils.isBlank(businessParams)) {
            logger.error("{}表业务分流参数不能为空", tableName);
            return Collections.emptyList();
        }
        var type = Integer.valueOf(businessParams);
        //发货地址
        if (AddressTypeEnum.isCustomer(type)) {
            return Arrays.asList(ScannerCodeEnum.CUSTOMER.getName());
        }
        //收货地址
        if (AddressTypeEnum.isReceiving(type)) {
            return Arrays.asList(ScannerCodeEnum.CONSIGNEE.getName());
        }
        //线上承运方
        if (AddressTypeEnum.isOnline(type)) {
            return Arrays.asList(ScannerCodeEnum.CARRIER_ONLINE.getName());
        }
        //线下承运方
        if (AddressTypeEnum.isOffline(type)) {
            return Arrays.asList(ScannerCodeEnum.CARRIER_OFFLINE.getName());
        }
        return Collections.emptyList();
    }

    private String params(String data) {
        var map = JSON.parseObject(data, Map.class);
        //地址表时，特殊处理，需要处理线上，线下承运方id，需手动区分承运方站点地址类型
        if (Objects.nonNull(map.get(Constants.ADDR_SUPPLIER_ID))) {
            //地址线上承运方站点类型
            map.put(ADDR_TYPE, AddressTypeEnum.ONLINE_CARRIER.getValue());
        }
        if (Objects.nonNull(map.get(Constants.ADDR_SYMBOL_ID))) {
            //地址线下承运方站点类型
            map.put(ADDR_TYPE, AddressTypeEnum.OFFLINE_CARRIER.getValue());
        }
        //businessParams 为 Addr_Type
        var businessParams = String.valueOf(map.get(ADDR_TYPE));
        logger.info("addr addr_type params : {}", businessParams);
        return businessParams;
    }
}
